/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cjava.system.bean.associate;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIData;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.cjava.system.bean.NavigationBean;
import org.cjava.system.bean.config.BenefitBean;
import org.cjava.system.model.ApertureAssociate;
import org.cjava.system.model.BusinessAssociate;
import org.cjava.system.model.Department;
import org.cjava.system.model.District;
import org.cjava.system.model.Person;
import org.cjava.system.model.Province;
import org.cjava.system.model.State;
import org.cjava.system.model.University;
import org.cjava.system.model.extra.TableBA;
import org.cjava.system.service.interfac.IApertureAssociateService;
import org.cjava.system.service.interfac.IBusinessAssociateService;
import org.cjava.system.service.interfac.IDepartmentService;
import org.cjava.system.service.interfac.IDistrictService;
import org.cjava.system.service.interfac.IPersonService;
import org.cjava.system.service.interfac.IProvinceService;
import org.cjava.system.service.interfac.ISystemUserService;
import org.cjava.system.service.interfac.IUniversityService;
import org.cjava.system.util.Clazz;
import org.cjava.system.util.faces.FacesUtil;
import org.omnifaces.util.Ajax;
import org.omnifaces.util.Components;
import org.primefaces.event.SelectEvent;

/**
 *
 * @author user
 */
@ManagedBean
@SessionScoped
public class BusinessAssociateBean implements Serializable {

    private static final long serialVersionUID = 1L;
    @ManagedProperty("#{businessAssociateService}")
    IBusinessAssociateService businessAssociateService;
    @ManagedProperty("#{personService}")
    IPersonService personService;
    @ManagedProperty("#{benefitBean}")
    BenefitBean benefitBean;
    @ManagedProperty("#{navigationBean}")
    NavigationBean navigationBean;
    @ManagedProperty("#{departmentService}")
    IDepartmentService departmentService;
    @ManagedProperty("#{provinceService}")
    IProvinceService provinceService;
    @ManagedProperty("#{districtService}")
    IDistrictService districtService;
    @ManagedProperty("#{universityService}")
    IUniversityService universityService;
    @ManagedProperty("#{apertureAssociateService}")
    IApertureAssociateService apertureAssociateService;
    @ManagedProperty("#{systemUserService}")
    ISystemUserService systemUserService;
    @ManagedProperty("#{clazz}")
    Clazz clazz;
    //////////////////////////////////////////////////
    private BusinessAssociate businessAssociate = new BusinessAssociate();
    private List<TableBA> listTableBA;
    private List<TableBA> listTableBAFilter;
    private List<BusinessAssociate> listBusinessAssociate;
    private List<BusinessAssociate> listBusinessAssociateFilter;
    private Person person = new Person();
    private Integer idDistrict;
    private BigDecimal priceAssociateCJava;
    private Double totalPriceDisconunt;
    ///////////////////////////////////////////////////////
    private List<University> listUniversity;
    private List<Department> listDepartment;
    private List<Province> listProvince;
    private List<District> listDistrict;
    private Integer idDepartment;
    private Integer idProvince;
    private University univesityAdd = new University();
    //////////////////////////////////////////////////
    private Integer searchFor = 1;
    boolean confirmRenovation = false;
    private Integer filterCard = 1;
    /////////////////////////////////////////////////
    private List<ApertureAssociate> listApertureAssociate;
    private Integer yearBusinessSearch = Calendar.getInstance().get(Calendar.YEAR);
    /////////////////////////////////////////////////
    private BusinessAssociate removeBusinessAssociate = new BusinessAssociate();
    //////////// PERIDA DE CARNET ////////////////////////

    public void prepareRemoveBussinessAssociate(Integer idBussinessAssociate) throws Exception {
        removeBusinessAssociate = businessAssociateService.getByHQL("from BusinessAssociate b where b.id=" + idBussinessAssociate);
    }
    
    public void initValues() throws Exception {
        univesityAdd = new University();
        idDistrict = null;
        listTableBA = null;
        listTableBAFilter = null;
        listUniversity = null;
        listDepartment = null;
        listProvince = null;
        idDepartment = null;
        //DESCUENTO POR DEFECTO EN 0%
        businessAssociate = new BusinessAssociate();
        businessAssociate.setDiscount(0);
        businessAssociate.setStartDate(new Date());
        ////////////////////////////////////
        person = new Person();
        filterCard = 1;
        listBusinessAssociate = null;
        benefitBean.initValueApertureAssociate();
        priceAssociateCJava = benefitBean.getApertureAssociate().getPricePerAssociate();
        // SI AUN NO ESTA CONFIGURADA LA EL PRECIO DE LA NUEVA APERTURA DE CARNET.
        //TIENE QUE REDIRECCIONAR A REGISTAR EL PRECIO
        if (priceAssociateCJava == null) {
            navigationBean.setNavigationContent("./pages/content/configuration/new_aperture_associate.xhtml");
            FacesUtil.getRequestContext().update("panelPrincipalId");
        } else {
            businessAssociate.setDiscount(0);
            Double total = (priceAssociateCJava.doubleValue()) - ((priceAssociateCJava.doubleValue()) * (double) (businessAssociate.getDiscount() / 100.00));
            totalPriceDisconunt = Clazz.ROUND(total, 2);

        }
    }

    public void changeStatePhotoCheck(Integer idBusinessAssociate) throws Exception {
        BusinessAssociate busTemp = businessAssociateService.getByHQL("from BusinessAssociate b where b.id=" + idBusinessAssociate);
        Person perTemp = busTemp.getIdPerson();
        if(perTemp.getPhotoCheck() == null )
            perTemp.setPhotoCheck(true);
        else
            perTemp.setPhotoCheck(!perTemp.getPhotoCheck());
        personService.update(perTemp);
        try {
            UIData table = (UIData) Components.findComponent("formAssDownId:tableAssId");
            //System.out.println("Tabla: " + table);
            Ajax.updateColumn(table, 7);
            listBusinessAssociate = null;
            listTableBA = null;
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        FacesUtil.addMessage("Foto Actualizada.", null, FacesMessage.SEVERITY_INFO);
    }
    
    public void searchAssociateForYearFilter() throws Exception {
        if (filterCard == 1) { //MOSTAR TODOS SI FUNCIONA
            State lostCard = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_PERDIDO,
                    Clazz._STATE._ENTITY._BusinessAssociate);

            String HQL = "select b.id as id, b.idPerson.dni as dni, b.codeCard as codeCard, "
                    + "b.idPerson.fatherName as fatherName, b.idPerson.motherName as motherName, b.idPerson.name as name, "
                    + "b.idPerson.email as email, b.codeCourse as codeCourse, b.idPerson.phone as phone, b.idPerson.photoCheck as photoCheck "
                    + "from BusinessAssociate b "
                    + "where b.idApertureAssociate.year=" + yearBusinessSearch
                    + " and b.idState.id!=" + lostCard.getId();
            listTableBA = businessAssociateService.listHQL(HQL, TableBA.class);
            listTableBAFilter = null;
            
        } else if (filterCard == 2) {//MOSTAR SOLO LOS QUE NO RECOGEN FUNCIONA

            String HQL = "select b.id as id, b.idPerson.dni as dni, b.codeCard as codeCard, "
                    + "b.idPerson.fatherName as fatherName, b.idPerson.motherName as motherName, b.idPerson.name as name, "
                    + "b.idPerson.email as email, b.codeCourse as codeCourse, b.idPerson.phone as phone, b.idPerson.photoCheck as photoCheck "
                    + "from BusinessAssociate b "
                    + "where b.idApertureAssociate.year=" + yearBusinessSearch
                    + " and (b.codeCard='' or b.codeCard=null)";
            listTableBA = businessAssociateService.listHQL(HQL, TableBA.class);
            listTableBAFilter = null;
        } else if (filterCard == 3) { //MOTRAR CARNET EN USO
            State lostCard = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_NUEVO,
                    Clazz._STATE._ENTITY._BusinessAssociate);

            String HQL = "select b.id as id, b.idPerson.dni as dni, b.codeCard as codeCard, "
                    + "b.idPerson.fatherName as fatherName, b.idPerson.motherName as motherName, b.idPerson.name as name, "
                    + "b.idPerson.email as email, b.codeCourse as codeCourse, b.idPerson.phone as phone, b.idPerson.photoCheck as photoCheck "
                    + "from BusinessAssociate b "
                    + "where b.idApertureAssociate.year=" + yearBusinessSearch
                    + " and (b.codeCard<>'' and b.codeCard!=null)"
                    + " and b.idState.id=" + lostCard.getId();
            listTableBA = businessAssociateService.listHQL(HQL, TableBA.class);
            listTableBAFilter = null;
        } else if (filterCard == 4) {
            State lostCard = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_PERDIDO,
                    Clazz._STATE._ENTITY._BusinessAssociate);

            String HQL = "select b.id as id, b.idPerson.dni as dni, b.codeCard as codeCard, "
                    + "b.idPerson.fatherName as fatherName, b.idPerson.motherName as motherName, b.idPerson.name as name, "
                    + "b.idPerson.email as email, b.codeCourse as codeCourse, b.idPerson.phone as phone, b.idPerson.photoCheck as photoCheck "
                    + "from BusinessAssociate b "
                    + "where b.idApertureAssociate.year=" + yearBusinessSearch
                    + " and (b.codeCard!='' and b.codeCard!=null)"
                    + " and b.idState=" + lostCard.getId();
            listTableBA = businessAssociateService.listHQL(HQL, TableBA.class);
            listTableBAFilter = null;
        } else if( filterCard == 5) {
            State newCard = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_NUEVO,
                    Clazz._STATE._ENTITY._BusinessAssociate);
            String hql = "select b.id as id, b.idPerson.dni as dni, b.codeCard as codeCard, "
                    + "b.idPerson.fatherName as fatherName, b.idPerson.motherName as motherName, b.idPerson.name as name, "
                    + "b.idPerson.email as email, b.codeCourse as codeCourse, b.idPerson.phone as phone, b.idPerson.photoCheck as photoCheck "
                    + "from BusinessAssociate b "
                    + "where b.idApertureAssociate.year=" + yearBusinessSearch
                    + " and b.idState.id=" + newCard.getId() 
                    + " and b.idPerson.id not in "
                    + "(select m.idPerson.id from BusinessAssociate m "
                    + "where m.idApertureAssociate.year<(year) and m.idState=(idState))"
                    .replace("(idState)", newCard.getId() + "")
                    .replace("(year)", "" + yearBusinessSearch);
            
            listTableBA = businessAssociateService.listHQL(hql, TableBA.class);
            listTableBAFilter = null;
        } else if( filterCard == 6) {
            State newCard = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_NUEVO,
                    Clazz._STATE._ENTITY._BusinessAssociate);
            String hql = "select b.id as id, b.idPerson.dni as dni, b.codeCard as codeCard, "
                    + "b.idPerson.fatherName as fatherName, b.idPerson.motherName as motherName, b.idPerson.name as name, "
                    + "b.idPerson.email as email, b.codeCourse as codeCourse, b.idPerson.phone as phone, b.idPerson.photoCheck as photoCheck "
                    + "from BusinessAssociate b "
                    + "where b.idApertureAssociate.year=" + yearBusinessSearch
                    + " and b.idState.id=" + newCard.getId() 
                    + " and b.idPerson.id in "
                    + "(select m.idPerson.id from BusinessAssociate m "
                    + "where m.idApertureAssociate.year<(year) and m.idState=(idState))"
                    .replace("(idState)", newCard.getId() + "")
                    .replace("(year)", "" + yearBusinessSearch);
            
            listTableBA = businessAssociateService.listHQL(hql, TableBA.class);
            listTableBAFilter = null;
        }

    }

    public void clearUniversity() {
        univesityAdd = new University();
    }

    public boolean appendYearToCodeCard() throws Exception {
        System.out.println("Cide: " + businessAssociate.getCodeCard());
        System.out.println("idDistrito: " + idDistrict);
        if (businessAssociate.getCodeCard() != null
                && !businessAssociate.getCodeCard().equals("")) {
            System.out.println(businessAssociate.getCodeCard());
            String exCode = businessAssociate.getIdApertureAssociate().getYear() + "" + businessAssociate.getCodeCard();
            System.out.println("Codigo de Entrada: " + exCode);
            String hql = "select a.id as id from BusinessAssociate a where "
                    + "a.codeCard='" + exCode + "'";
            //ENTRA SI ES PARA ACTUALIZAR
            if (businessAssociate.getId() != null) {
                hql = "select a.id as id from BusinessAssociate a where "
                        + "a.id!=" + businessAssociate.getId() + " and a.codeCard='" + exCode + "'";
            }
            List<Integer> idCodes = businessAssociateService.listHQL(hql);
            //NO ENCONTRO NINGUN CODIGO UTILIZADO
            if (idCodes.isEmpty()) {
                businessAssociate.setCodeCard(exCode);
                return true;
            } else {
                // ENCONTRO UN CODIGO UTILIZDO POR LO QUE DEBE NUEVAMENTE INGRESAR 
                //OTRO CODIGO
                FacesUtil.addMessage("El Código ya esta siendo utilizado...", null, FacesMessage.SEVERITY_ERROR);
                //FacesUtil.addMessage("Ingrese otro código...", null, FacesMessage.SEVERITY_INFO);
                return false;
            }
        } else {
            return true;
        }
    }

    /**
     * Guarda a la persona junto con los datos, los socios y su código generado.
     *
     * @throws Exception
     */
    public void saveOrUpdatePersonAndAssociate() throws Exception {
        System.out.println("idDistrito: " + idDistrict);
        if (person != null && idDistrict != null && idDistrict != 0) {
            person.setIdDistrict(new District(idDistrict));
        }
        if (appendYearToCodeCard()) {
            String hql = "select max(a.code) from BusinessAssociate a "
                    + "where a.idApertureAssociate.year="
                    + businessAssociate.getIdApertureAssociate().getYear();

            List<String> listCode = businessAssociateService.listHQL(hql);
            //System.out.println("LMax Doce: " + listCode.get(0));
            Integer codeGenerator;
            if (!listCode.isEmpty()) {
                codeGenerator = (businessAssociate.getIdApertureAssociate().getYear() * 100000) + 1;
            } else {
                codeGenerator = Integer.parseInt(listCode.get(0)) + 1;
            }
            //System.out.println("LMax Doce: " + listCode.get(0));
            //System.out.println("Codigo Generado: " + codeGenerator);
            ///////////GUARDADO PERSONA
            if (person.getId() == null) {

                person.setStartDate(businessAssociate.getStartDate());

                businessAssociate.setCode("" + codeGenerator);
                //businessAssociate.setStartDate(person.getStartDate());
                //businessAssociate.setIdPerson(person);
                businessAssociate
                        .setPricePerAssociate(businessAssociate
                                .getIdApertureAssociate().getPricePerAssociate());
                State sTemp = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_NUEVO, Clazz._STATE._ENTITY._BusinessAssociate);
                businessAssociate.setIdState(sTemp);

                Integer idPerson = personService.save(person);
                person.setId(idPerson);
                businessAssociate.setIdPerson(person);

                businessAssociateService.save(businessAssociate);
                this.initValues();
//                idDistrict = null;
//                businessAssociate = new BusinessAssociate();
//                person = new Person();
                FacesUtil.addMessage("Nuevo socio registrado", null, FacesMessage.SEVERITY_INFO);
            } else {
                personService.update(person);
                //SOLO SI ES QUE NUNCA FUE REGISTRADO COMO SOCIO
                businessAssociate.setIdPerson(person);
                //CARGA LA FECHA, VERIFICANDO SI ES QUE ES PARA ACTUALIZAR O SI ES NUEVO EL SOCIO

                if (businessAssociate.getId() == null) {
                    businessAssociate.setCode("" + codeGenerator);
                    //businessAssociate.setStartDate(person.getStartDate());
                    //businessAssociate.setIdPerson(person);
                    businessAssociate
                            .setPricePerAssociate(businessAssociate
                                    .getIdApertureAssociate().getPricePerAssociate());
                    State sTemp = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_NUEVO, Clazz._STATE._ENTITY._BusinessAssociate);
                    businessAssociate.setIdState(sTemp);
                    businessAssociateService.save(businessAssociate);
                    FacesUtil.addMessage("Registrado como socio", null, FacesMessage.SEVERITY_INFO);
                } else {
                    businessAssociateService.update(businessAssociate);
                    if (businessAssociate.getIdSystemUser() != null) {
                        businessAssociate
                                .getIdSystemUser()
                                .setUserName(person.getEmail());
                        systemUserService.update(businessAssociate.getIdSystemUser());
                    }
                }
                this.initValues();
//                businessAssociate = new BusinessAssociate();
//                person = new Person();
//                idDistrict = null;
                FacesUtil.addMessage("Datos Actualizado...", null, FacesMessage.SEVERITY_INFO);
            }
        }
    }

    public void updateProvince() throws Exception {
        listProvince = provinceService.listHQL("from Province p where p.idDepartment.id=" + idDepartment);
    }

    public void updateDistrict() throws Exception {
        listDistrict = districtService.listHQL("from District d where d.idProvince.id=" + idProvince);
    }

    public void postProcessXLS(Object document) {
        HSSFWorkbook wb = (HSSFWorkbook) document;
        HSSFSheet sheet = wb.getSheetAt(0); //nueva hoja
        HSSFRow header = sheet.getRow(0); //primera fila

        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        //DNI, CODE CARD, APPE Y NOMBRES, CORREOS
        header.getCell(0).setCellStyle(cellStyle);
        header.getCell(0).setCellValue("DNI");
        header.getCell(1).setCellStyle(cellStyle);
        header.getCell(1).setCellValue("CODIGO CARNET");
        header.getCell(2).setCellStyle(cellStyle);
        header.getCell(2).setCellValue("APELLIDOS Y NOMBRES");
        header.getCell(3).setCellStyle(cellStyle);
        header.getCell(3).setCellValue("CORREOS");
        header.getCell(4).setCellStyle(cellStyle);
        header.getCell(4).setCellValue("COD. CURSO");
        header.getCell(5).setCellStyle(cellStyle);
        header.getCell(5).setCellValue("CELULAR");
        header.getCell(6).setCellStyle(cellStyle);
        header.getCell(6).setCellValue("FOTO");
//        header.getCell(7).setCellStyle(cellStyle);
//        header.getCell(7).setCellValue("CÓDIGO CURSO");
        for (int i = 0; i < listTableBA.size(); i++) {
            HSSFRow row = sheet.getRow(i + 1); //FILA
//            HSSFCell cell = row.getCell(i); //CELDA
            row.getCell(0).setCellValue(
                    listTableBA
                    .get(i)
                    .getDni()
            );
            row.getCell(1).setCellValue(
                    listTableBA
                    .get(i)
                    .getCodeCard() == null ? "" : listTableBA
                    .get(i)
                    .getCodeCard()
            );
            row.getCell(2).setCellValue(
                    listTableBA
                    .get(i)
                    .getCompleteName() == null ? "" : listTableBA
                    .get(i)
                    .getCompleteName()
            );
            row.getCell(3).setCellValue(
                    listTableBA
                    .get(i)
                    .getEmail() == null ? "" : listTableBA
                    .get(i)
                    .getEmail()
            );
            
            row.getCell(4).setCellValue(
                    listTableBA
                    .get(i)
                    .getCodeCourse() == null ? "" : listTableBA
                    .get(i).getCodeCourse()
            );
            row.getCell(5).setCellValue(
                    listTableBA
                    .get(i)
                    .getPhone() == null ? "" : listTableBA
                    .get(i).getPhone()
            );
            row.getCell(6).setCellValue(
                    listTableBA
                    .get(i)
                    .getPhotoCheck()== null ? false : listTableBA
                    .get(i).getPhotoCheck()
            );
        }
    }

    public void saveOrUpdateUniversity() throws Exception {
        if (univesityAdd.getId() == null) {
            universityService.save(univesityAdd);
            listUniversity.add(univesityAdd);
            FacesUtil.addMessage("Guardado con éxito", null, FacesMessage.SEVERITY_INFO);
        } else {
            universityService.update(univesityAdd);
            listUniversity = null;
            FacesUtil.addMessage("Actualizado con éxito", null, FacesMessage.SEVERITY_INFO);
        }
    }

    public void initValuesForRenovation() {
        person = new Person();
        businessAssociate = new BusinessAssociate();
        businessAssociate.setStartDate(Calendar.getInstance().getTime());
        confirmRenovation = false;
        searchFor = 1;
    }

    /**
     * EVENTO DE UN WITGET AUTOCOMPLETABLE AQUI VERIFICA SI ES QUE TIENE O NO
     * RENOVACIÓN
     *
     * @param event
     */
    public void selectCallSheetCharges1(SelectEvent event) throws Exception {
        if (event.getObject() != null) {
            System.out.println("Objeto no nulo: " + event.getObject());
            Person personTemp = ((Person) event.getObject());
            String verifiHQL = "select b.id from BusinessAssociate b where "
                    + "b.idApertureAssociate.year=" + Calendar.getInstance().get(Calendar.YEAR)
                    + " and b.idPerson.id=" + personTemp.getId();
            List<Integer> listBATemp = businessAssociateService.listHQL(verifiHQL);
            if (!listBATemp.isEmpty()) {
                confirmRenovation = false;
                FacesUtil.addMessage("Ya es Socios del año " + Calendar.getInstance().get(Calendar.YEAR), null, FacesMessage.SEVERITY_WARN);
            } else {
                State state = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_NUEVO, Clazz._STATE._ENTITY._BusinessAssociate);
                String hql = "from BusinessAssociate s where s.idState.id=" + state.getId()
                        + " and s.idPerson.id=" + personTemp.getId()
                        + " and s.idApertureAssociate.year="
                        + "(select max(a.year) from ApertureAssociate a where a.year!=" + Calendar.getInstance().get(Calendar.YEAR) + ")";
                List<BusinessAssociate> listBAATemp = businessAssociateService.listHQL(hql);
                if (!listBAATemp.isEmpty()) {
                    // ENCONTRO UN EX-SOCIO
                    System.out.println(listBAATemp.size());
                    confirmRenovation = true;
                    businessAssociate = listBAATemp.get(0);
                    businessAssociate.setStartDate(Calendar.getInstance().getTime());
                    businessAssociate.setCodeCard(null);
                    FacesUtil.addMessage("Listo para realizar la renovación", null, FacesMessage.SEVERITY_INFO);
                } else {
                    FacesUtil.addMessage("Nunca fué Socio", null, FacesMessage.SEVERITY_WARN);
                    businessAssociate = new BusinessAssociate();
                    //FacesUtil.addMessage("Registre como Socio", null, FacesMessage.SEVERITY_WARN);
                    navigationBean.setNavigationContent("./pages/content/business_associate/new_associate.xhtml");
                    searchPersonForRegisterAssociate();
                    FacesUtil.getRequestContext().update("panelPrincipalId");
                }

            }

        } else {
            System.out.println("Objeto nulo");
            confirmRenovation = false;
            FacesUtil.addMessage("Intentelo nuevamenete.", null, FacesMessage.SEVERITY_WARN);
        }
    }

    public void saveRenovationAssociate() throws Exception {
        businessAssociate.setId(null);
        businessAssociate.setDiscount(0);
        businessAssociate.setPricePerAssociate(BigDecimal.ZERO);

        if (businessAssociate.getCodeCard() != null && !businessAssociate.getCodeCard().isEmpty()) {
            //SI ES QUE EL CÓDIGO ES DIFERENTE DE NULO. SI A LLENADO ALGO
            String hql = "from ApertureAssociate a where a.year=" + Calendar.getInstance().get(Calendar.YEAR);
            List<ApertureAssociate> listApertureAss = apertureAssociateService.listHQL(hql);
            if (listApertureAss.isEmpty()) {
                //SI ES QUE NO EXISTE UNA APERTURA DE ESTE AÑO DEBE MANDAR A CONFIGURAR
                FacesUtil.addMessage("Falta Configurár el año...", null, FacesMessage.SEVERITY_WARN);
                navigationBean.setNavigationContent("./pages/content/configuration/new_aperture_associate.xhtml");
                benefitBean.initValueApertureAssociate();
            } else {
                //EXISTE UNA APERTURA PARA ESTE AÑO, SOLO DEBE GUARDAR,.
                String codeGenerate = listApertureAss.get(0).getYear() + "" + businessAssociate.getCodeCard();
                String hqlCard = "select c.id from BusinessAssociate c "
                        + "where c.codeCard='" + codeGenerate + "'";
                List<Integer> listIdsCode = businessAssociateService.listHQL(hqlCard);
                if (listIdsCode.isEmpty()) {
                    businessAssociate.setCodeCard(codeGenerate);
                    businessAssociate.setIdApertureAssociate(listApertureAss.get(0));
                    businessAssociateService.save(businessAssociate);
                    businessAssociate = new BusinessAssociate();
                    confirmRenovation = false;
                    FacesUtil.addMessage("Renovado con éxito...", null, FacesMessage.SEVERITY_INFO);
                } else {
                    FacesUtil.addMessage("El Código esta ocupado", null, FacesMessage.SEVERITY_ERROR);
                }
//                businessAssociate.setIdApertureAssociate(listApertureAss.get(0));
//
//                businessAssociateService.save(businessAssociate);
//                FacesUtil.addMessage("Renovación de Socio Exitosa...", null, FacesMessage.SEVERITY_INFO);
            }

//
//            }
        } else {
            //SI ES QUE EL CÓDIGO ES NULO O NO LLENO NADA
            String hql = "from ApertureAssociate a where a.year=" + Calendar.getInstance().get(Calendar.YEAR);
            List<ApertureAssociate> listApertureAss = apertureAssociateService.listHQL(hql);
            if (listApertureAss.isEmpty()) {
                //SI ES QUE NO EXISTE UNA APERTURA DE ESTE AÑO DEBE MANDAR A CONFIGURAR
                FacesUtil.addMessage("Falta Configurár el año...", null, FacesMessage.SEVERITY_WARN);
                navigationBean.setNavigationContent("./pages/content/configuration/new_aperture_associate.xhtml");
                benefitBean.initValueApertureAssociate();
            } else {
                businessAssociate.setIdApertureAssociate(listApertureAss.get(0));
                businessAssociateService.save(businessAssociate);
                businessAssociate = new BusinessAssociate();
                confirmRenovation = false;
                FacesUtil.addMessage("Renovado con éxito...", null, FacesMessage.SEVERITY_INFO);
            }
        }
       
    }

    /**
     * BUSQUEDA DE LA VISTA EN EL AUTO COMPLETABLE
     *
     * @param query
     * @return
     */
    public List<Person> autocompleteSearch(String query) {
        query = query.trim().toLowerCase();
        String SQL = "";
        if (searchFor == 1) {
            SQL = "SELECT p.id as id, p.dni as dni, p.name as name, p.father_name as fatherName, "
                    + "p.mother_name as motherName"
                    + " FROM person p where p.dni like '" + query + "%'";
        } else {
            SQL = "SELECT p.id as id, p.dni as dni, p.name as name, p.father_name as fatherName, "
                    + "p.mother_name as motherName"
                    + " FROM person p where lower(concat(p.father_name,' ',p.mother_name,' ',p.name)) like '" + query + "%'";
        }

        List<Person> listTempPerson = new ArrayList<>();
        try {
            listTempPerson = personService.listSQL(SQL);
            System.out.println(listTempPerson.size());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return listTempPerson;
    }

    public void editPerson(Integer idBusinessAssociate) throws Exception {
        businessAssociate = businessAssociateService.getByHQL("from BusinessAssociate b where b.id=" + idBusinessAssociate);
        person = businessAssociate.getIdPerson();
        if (businessAssociate.getCodeCard() != null && businessAssociate.getCodeCard().length() == 8) {
            String codeSep = businessAssociate.getCodeCard();
            businessAssociate.setCodeCard(codeSep.substring(4));

            System.out.println(codeSep);
            System.out.println(codeSep.substring(4));
        }
        if (person.getIdDistrict() != null) {
            idDistrict = person.getIdDistrict().getId();
            listDistrict = new ArrayList<District>();
            listDistrict.add(person.getIdDistrict());
        }
    }
    
    /**
     * De la vista "view_associate.xhtml" pasara a la vista
     * "new_associate.xhtml" para poder editar correctamente a la persona.
     */
    public void editPerson() {
        if (businessAssociate.getCodeCard() != null && businessAssociate.getCodeCard().length() == 8) {
            String codeSep = businessAssociate.getCodeCard();
            businessAssociate.setCodeCard(codeSep.substring(4));

            System.out.println(codeSep);
            System.out.println(codeSep.substring(4));
        }
        if (person.getIdDistrict() != null) {
            idDistrict = person.getIdDistrict().getId();
            listDistrict = new ArrayList<District>();
            listDistrict.add(person.getIdDistrict());
        }
    }

    /**
     *
     */
    public void searchPersonForRegisterAssociate() throws Exception {
        System.out.println("Buscando Persona Por DNI...");
        String hql = "from Person p where p.dni='" + person.getDni() + "'";
        List<Person> listPTemp = personService.listHQL(hql);
        if (!listPTemp.isEmpty()) {
            //EXISTE UNA PERSONA CON ESE DNI
            hql = "select b.id, b.idApertureAssociate.year as id from BusinessAssociate b where "
                    + "b.idPerson.dni='" + person.getDni() + "'";
            List<Object[]> listInt = businessAssociateService
                    .listHQL(hql);

            if (listInt.isEmpty()) {
                //ESTA PERSONA DEBE HACER RENOVACIÓN Y NO REGISTRARSE COMO SOCIO
                //if(listInt)
                Object []row = listInt.get(0);
                System.out.println("Row: " + row[0] + " - " + row[1]);
                if(Calendar.getInstance().get(Calendar.YEAR) == (Integer)row[1]) {
                    FacesUtil.addMessage("Ya es Socio de este año", null, FacesMessage.SEVERITY_WARN);
                } else {
                    FacesUtil.addMessage("Debes Ronovar, es un ex-socio", null, FacesMessage.SEVERITY_WARN);
                }
                
                //FacesUtil.addMessage("Quizá deba renovar...", null, FacesMessage.SEVERITY_WARN);
                //navigationBean.setNavigationContent("./pages/con");
            } else {
                //NO SE ENCONTRO NINGUN SOCIO, PERO SI DATOS DE LA PERSONA.
                person = listPTemp.get(0);
                if (person.getIdDistrict() != null) {
                    idDistrict = person.getIdDistrict().getId();
                    listDistrict = new ArrayList<District>();
                    listDistrict.add(person.getIdDistrict());
                }
                FacesUtil.addMessage("Ingrese solo los campos faltantes...", null, FacesMessage.SEVERITY_INFO);
            }

        } else {
            //MOSTRAR EL FORMULARIO COMPLETO
            FacesUtil.addMessage("Complete todo el formulario.", null, FacesMessage.SEVERITY_INFO);
            String dni = person.getDni();
            initValues();
            person.setDni(dni);
            
        }
    }

    /**
     * remover de los socios a un miembro ya perteneciente
     *
     * @throws java.lang.Exception
     */
    public void removeAssociate() throws Exception {
        person = new Person();
        businessAssociate = new BusinessAssociate();
        businessAssociateService.delete(removeBusinessAssociate);
        removeBusinessAssociate = new BusinessAssociate();
        listTableBA = null;
        listTableBAFilter = null;
        listBusinessAssociate = null;
        listBusinessAssociateFilter = null;
        FacesUtil.addMessage("Eliminado Correctamente...", null, FacesMessage.SEVERITY_INFO);
    }

    public void initValuesViewAssociate() {
        listApertureAssociate = null;
        yearBusinessSearch = null;
        listTableBA = null;
        listBusinessAssociate = null;
        listBusinessAssociateFilter = null;
        listTableBAFilter = null;
        yearBusinessSearch = null;
    }

    public void calculator() {
        System.out.println("Entrando al listener");
        System.out.println(businessAssociate.getDiscount());
        Double total = (priceAssociateCJava.doubleValue()) - ((priceAssociateCJava.doubleValue()) * (double) (businessAssociate.getDiscount() / 100.00));
        totalPriceDisconunt = Clazz.ROUND(total, 2);
        System.out.println(totalPriceDisconunt);
    }

    public void saveOrUpdatePerson() throws Exception {
        if (person.getId() == null) {
            System.out.println("Creando uno nuevo");
            person.setIdDistrict(new District(idDistrict));
            person.setStartDate(new Date());

            personService.save(person);
            FacesUtil.addMessage("Siguiente paso, para confirmar el guardado.", null, FacesMessage.SEVERITY_INFO);
        } else {
            System.out.println("Pasando a editar...");
            person.setIdDistrict(new District(idDistrict));

            personService.update(person);
            FacesUtil.addMessage("Actualizado Correcto...", null, FacesMessage.SEVERITY_INFO);
        }

    }

    public void saveOrUpdateAssociate() throws Exception {
        if (businessAssociate.getId() == null) {
            businessAssociate.setIdPerson(person);
            businessAssociate.setIdApertureAssociate(benefitBean.getApertureAssociate());
            businessAssociate.setStartDate(new Date());
            businessAssociate.setPricePerAssociate(priceAssociateCJava);

            businessAssociateService.save(businessAssociate);

            FacesUtil.addMessage("Guardado con éxito", null, FacesMessage.SEVERITY_INFO);
        } else {
            businessAssociateService.update(businessAssociate);
            FacesUtil.addMessage("Actualizado con éxito", null, FacesMessage.SEVERITY_INFO);
        }
    }

//    public void searchPersonOrAssociate2() throws Exception {
//        State state = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_VIGENTE, Clazz._STATE._ENTITY._BusinessAssociate);
//        String hql = "from BusinessAssociate b where b.idState.id=" + state.getId() + " and "
//                + "b.idApertureAssociate.year=" + Calendar.getInstance().get(Calendar.YEAR);
//        List<BusinessAssociate> listBATemp = businessAssociateService.listHQL(hql);
//        if (!listBATemp.isEmpty()) {
//            //YA ES SOCIO Y DEBE MOSTRAR SU PERFIL.
//        } else {
//            state = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_NO_VIGENTE, Clazz._STATE._ENTITY._BusinessAssociate);
//            hql = "from BusinessAssociate b where b.idState.id=" + state.getId()
//                    + " and b.idApertureAssociate.year="
//                    + "(select max(a.year) from ApertureAssociate a where a.year!=" + Calendar.getInstance().get(Calendar.YEAR) + ")";
//            listBATemp = businessAssociateService.listHQL(hql);
//            if (!listBATemp.isEmpty()) {
//                //ES UN EX SOCIO, ARROJA EL ULTIMO AÑO EN QUE SE REGISTRO
//            } else {
//                hql = "from Person p";
//                List<Person> listPTemp = personService.listHQL(hql);
//                if (!listPTemp.isEmpty()) {
//                    //EXISTE LA PERSONA. SE DEBE REGISTRAR COMO SOCIO
//                } else {
//                    // NO PERTENECE A NINGUNA DE LAS OPCIONES 
//                    // POR LO QUE SE DEBE REGISTRAR COMPLETAMENTE.
//                }
//            }
//
//        }
//    }
    public BusinessAssociate getBusinessAssociate() {
        return businessAssociate;
    }

    public void setBusinessAssociate(BusinessAssociate businessAssociate) {
        this.businessAssociate = businessAssociate;
    }

    public List<BusinessAssociate> getListBusinessAssociate() throws Exception {
        if (listBusinessAssociate == null) {
            State lostCard = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_PERDIDO,
                    Clazz._STATE._ENTITY._BusinessAssociate);
            String HQL = "from BusinessAssociate b "
                    + "where b.idApertureAssociate.year="
                    + yearBusinessSearch
                    + " and b.idState.id!=" + lostCard.getId();
            listBusinessAssociate = businessAssociateService.listHQL(HQL);
        }
        return listBusinessAssociate;
    }

    public Double getTotalPriceDisconunt() {
        return totalPriceDisconunt;
    }

    public Integer getFilterCard() {
        return filterCard;
    }

    public void setFilterCard(Integer filterCard) {
        this.filterCard = filterCard;
    }

    public List<University> getListUniversity() throws Exception {
        if (listUniversity == null) {
            listUniversity = universityService.list();
        }
        return listUniversity;
    }

    public void setListUniversity(List<University> listUniversity) {
        this.listUniversity = listUniversity;
    }

    public void setSystemUserService(ISystemUserService systemUserService) {
        this.systemUserService = systemUserService;
    }

    public void setTotalPriceDisconunt(Double totalPriceDisconunt) {
        this.totalPriceDisconunt = totalPriceDisconunt;
    }

    public Integer getSearchFor() {
        return searchFor;
    }

    public void setSearchFor(Integer searchFor) {
        this.searchFor = searchFor;
    }

    public BusinessAssociate getRemoveBusinessAssociate() {
        return removeBusinessAssociate;
    }

    public void setRemoveBusinessAssociate(BusinessAssociate removeBusinessAssociate) {
        this.removeBusinessAssociate = removeBusinessAssociate;
    }

    public Integer getIdDistrict() {
        return idDistrict;
    }

    public BenefitBean getBenefitBean() {
        return benefitBean;
    }

    public void setBenefitBean(BenefitBean benefitBean) {
        this.benefitBean = benefitBean;
    }

    public BigDecimal getPriceAssociateCJava() {
        return priceAssociateCJava;
    }

    public void setPriceAssociateCJava(BigDecimal priceAssociateCJava) {
        this.priceAssociateCJava = priceAssociateCJava;
    }

    public void setIdDistrict(Integer idDistrict) {
        this.idDistrict = idDistrict;
    }

    public NavigationBean getNavigationBean() {
        return navigationBean;
    }

    public boolean isConfirmRenovation() {
        return confirmRenovation;
    }

    public Clazz getClazz() {
        return clazz;
    }

    public void setConfirmRenovation(boolean confirmRenovation) {
        this.confirmRenovation = confirmRenovation;
    }

    public void setNavigationBean(NavigationBean navigationBean) {
        this.navigationBean = navigationBean;
    }

    public void setListBusinessAssociate(List<BusinessAssociate> listBusinessAssociate) {
        this.listBusinessAssociate = listBusinessAssociate;
    }

    public void setBusinessAssociateService(IBusinessAssociateService businessAssociateService) {
        this.businessAssociateService = businessAssociateService;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public void setPersonService(IPersonService personService) {
        this.personService = personService;
    }

    public void setUniversityService(IUniversityService universityService) {
        this.universityService = universityService;
    }

    public void setClazz(Clazz clazz) {
        this.clazz = clazz;
    }

    public List<Department> getListDepartment() throws Exception {
        if (listDepartment == null) {
            listDepartment = departmentService.list();
        }
        return listDepartment;
    }

    public void setListDepartment(List<Department> listDepartment) {
        this.listDepartment = listDepartment;
    }

    public List<Province> getListProvince() {
        return listProvince;
    }

    public void setListProvince(List<Province> listProvince) {
        this.listProvince = listProvince;
    }

    public List<District> getListDistrict() {
        return listDistrict;
    }

    public void setListDistrict(List<District> listDistrict) {
        this.listDistrict = listDistrict;
    }

    public void setDepartmentService(IDepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    public void setProvinceService(IProvinceService provinceService) {
        this.provinceService = provinceService;
    }

    public void setDistrictService(IDistrictService districtService) {
        this.districtService = districtService;
    }

    public University getUnivesityAdd() {
        return univesityAdd;
    }

    public void setUnivesityAdd(University univesityAdd) {
        this.univesityAdd = univesityAdd;
    }

    public Integer getIdDepartment() {
        return idDepartment;
    }

    public void setIdDepartment(Integer idDepartment) {
        this.idDepartment = idDepartment;
    }

    public Integer getIdProvince() {
        return idProvince;
    }

    public List<BusinessAssociate> getListBusinessAssociateFilter() {
        return listBusinessAssociateFilter;
    }

    public void setListBusinessAssociateFilter(List<BusinessAssociate> listBusinessAssociateFilter) {
        this.listBusinessAssociateFilter = listBusinessAssociateFilter;
    }

    public void setIdProvince(Integer idProvince) {
        this.idProvince = idProvince;
    }

    public Integer getYearBusinessSearch() {
        return yearBusinessSearch;
    }

    public void setYearBusinessSearch(Integer yearBusinessSearch) {
        this.yearBusinessSearch = yearBusinessSearch;
    }

    public List<ApertureAssociate> getListApertureAssociate() throws Exception {
        if (listApertureAssociate == null) {
            String hql = "from ApertureAssociate a order by "
                    + "a.year desc";
            listApertureAssociate = apertureAssociateService.listHQL(hql);
            if (listApertureAssociate.isEmpty()) {
                ApertureAssociate aper = new ApertureAssociate();
                aper.setDescription("Descripción Default");
                aper.setPricePerAssociate(BigDecimal.ZERO);
                aper.setYear(Calendar.getInstance().get(Calendar.YEAR));
                apertureAssociateService.save(aper);
                listApertureAssociate.add(aper);
            }

        }

        return listApertureAssociate;
    }

    public List<TableBA> getListTableBA() throws Exception {
        if (listTableBA == null) {
            State lostCard = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_PERDIDO,
                    Clazz._STATE._ENTITY._BusinessAssociate);
            String HQL = "select b.id as id, b.idPerson.dni as dni, b.codeCard as codeCard, "
                    + "b.idPerson.fatherName as fatherName, b.idPerson.motherName as motherName, b.idPerson.name as name, "
                    + "b.idPerson.email as email, b.codeCourse as codeCourse, b.idPerson.phone as phone, b.idPerson.photoCheck as photoCheck "
                    + "from BusinessAssociate b "
                    + "where b.idApertureAssociate.year="
                    + yearBusinessSearch
                    + " and b.idState.id!=" + lostCard.getId();
            listTableBA = businessAssociateService.listHQL(HQL, TableBA.class);
        }
        return listTableBA;
    }

    public void setListTableBA(List<TableBA> listTableBA) {
        this.listTableBA = listTableBA;
    }

    public void setListApertureAssociate(List<ApertureAssociate> listApertureAssociate) {
        this.listApertureAssociate = listApertureAssociate;
    }

    public void setApertureAssociateService(IApertureAssociateService apertureAssociateService) {
        this.apertureAssociateService = apertureAssociateService;
    }

    public List<TableBA> getListTableBAFilter() {
        return listTableBAFilter;
    }

    public void setListTableBAFilter(List<TableBA> listTableBAFilter) {
        this.listTableBAFilter = listTableBAFilter;
    }

}
